package com.zuo.mall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.zuo.mall.common.api.CommonPage;
import com.zuo.mall.dto.PmsProductParam;
import com.zuo.mall.dto.PmsProductQueryParam;
import com.zuo.mall.dto.PmsProductResult;
import com.zuo.mall.entity.*;
import com.zuo.mall.mapper.PmsProductMapper;
import com.zuo.mall.service.*;
import org.apache.ibatis.annotations.Mapper;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.List;

@Service
public class PmsProductServiceImpl extends ServiceImpl<PmsProductMapper, PmsProduct> implements PmsProductService {

    @Autowired
    private CmsPrefrenceAreaProductRelationService prefrenceAreaProductRelationService;

    @Autowired
    private CmsSubjectProductRelationService subjectProductRelationService;

    @Autowired
    private PmsProductAttributeValueService productAttributeValueService;

    @Autowired
    private PmsProductLadderService productLadderService;

    @Autowired
    private PmsProductFullReductionService productFullReductionService;

    @Autowired
    private PmsMemberPriceService memberPriceService;


    @Autowired
    private PmsSkuStockService skuStockService;


    @Autowired
    private PmsProductAttributeService productAttributeService;


    @Autowired
    private CmsSubjectService cmsSubjectService;

    @Autowired
    private CmsPrefrenceAreaService cmsPrefrenceAreaService;


    private static final Logger LOGGER = LoggerFactory.getLogger(PmsProductServiceImpl.class);
    @Override
    public CommonPage<PmsProduct> list(PmsProductQueryParam productQueryParam) {
        int start = PageUtil.getStart(productQueryParam.getPageNum() - 1, productQueryParam.getPageSize());
        int end = PageUtil.getEnd(productQueryParam.getPageNum() - 1, productQueryParam.getPageSize());

        LambdaQueryWrapper<PmsProduct> queryWrapper = new LambdaQueryWrapper<>();

        // 关键字
        String keyword = productQueryParam.getKeyword();
        if (!StrUtil.isEmpty(keyword)) {
            queryWrapper.like(PmsProduct::getName, keyword);
        }

        // 商品货号
        String productSn = productQueryParam.getProductSn();
        if (!StrUtil.isEmpty(productSn)) {
            queryWrapper.eq(PmsProduct::getProductSn, productSn);
        }

        // 上架状态
        Integer publishStatus = productQueryParam.getPublishStatus();
        if (publishStatus != null) {
            queryWrapper.eq(PmsProduct::getPublishStatus, publishStatus);
        }

        // 审核状态
        Integer verifyStatus = productQueryParam.getVerifyStatus();
        if (verifyStatus != null) {
            queryWrapper.eq(PmsProduct::getVerifyStatus, verifyStatus);
        }

        // 分类Id
        Long productCategoryId = productQueryParam.getProductCategoryId();
        if (productCategoryId != null) {
            queryWrapper.eq(PmsProduct::getProductCategoryId, productCategoryId);
        }

        // 品牌
        Long brandId = productQueryParam.getBrandId();
        if (brandId != null) {
            queryWrapper.eq(PmsProduct::getBrandId, brandId);
        }
        queryWrapper.eq(PmsProduct::getDeleteStatus, 0);
        Integer total = baseMapper.selectCount(queryWrapper);

        // 分页
        queryWrapper.last("LIMIT " + start + "," + productQueryParam.getPageSize());
        List<PmsProduct> pmsProducts = baseMapper.selectList(queryWrapper);


        CommonPage<PmsProduct> pmsBrandCommonPage = CommonPage.restPage(pmsProducts);
        pmsBrandCommonPage.setTotal(Long.valueOf(total.toString()));
        pmsBrandCommonPage.setTotalPage(total / productQueryParam.getPageSize() + 1);

        return pmsBrandCommonPage;
    }

    @Override
    @Transactional
    public int create(PmsProductParam pmsProductParam) {
        // 首先插入商品表
        int insert = baseMapper.insert(pmsProductParam);
        // 获取到Id
        Long productId = pmsProductParam.getId();
        // 商品阶梯价格
        relateAndInsertList(productLadderService, pmsProductParam.getProductLadderList(), productId);
        // 商品满减价格
        relateAndInsertList(productFullReductionService, pmsProductParam.getProductFullReductionList(), productId);
        // 商品会员价格
        relateAndInsertList(memberPriceService, pmsProductParam.getMemberPriceList(), productId);
        // 商品库存信息
        relateAndInsertList(skuStockService, pmsProductParam.getSkuStockList(), productId);
        // 商品自定义参数规格属性
        relateAndInsertList(productAttributeValueService, pmsProductParam.getProductAttributeValueList(), productId);
        // 商品专题
        relateAndInsertList(subjectProductRelationService, pmsProductParam.getSubjectProductRelationList(), productId);
        // 商品优选专区
        relateAndInsertList(prefrenceAreaProductRelationService, pmsProductParam.getPrefrenceAreaProductRelationList(), productId);

        return insert;
    }

    @Override
    public int updatePublishStatusBatch(List<Long> productIdList, Integer publishStatus) {

        LambdaUpdateWrapper<PmsProduct> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(PmsProduct::getPublishStatus, publishStatus);
        updateWrapper.in(PmsProduct::getId, productIdList);
        this.update(updateWrapper);
        return productIdList.size();
    }

    @Override
    public int updateRecommendStatusBatch(List<Long> productIdList, Integer recommendStatus) {
        LambdaUpdateWrapper<PmsProduct> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(PmsProduct::getRecommandStatus, recommendStatus);
        updateWrapper.in(PmsProduct::getId, productIdList);
        return productIdList.size();
    }

    @Override
    public int updateNewStatusBatch(List<Long> ids, Integer newStatus) {
        LambdaUpdateWrapper<PmsProduct> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(PmsProduct::getNewStatus, newStatus);
        updateWrapper.in(PmsProduct::getId, ids);
        return ids.size();
    }
    @Override
    public int updateDeleteStatusBatch(List<Long> ids, Integer deleteStatus) {
        LambdaUpdateWrapper<PmsProduct> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(PmsProduct::getDeleteStatus, deleteStatus);
        updateWrapper.in(PmsProduct::getId, ids);
        return ids.size();
    }

    @Override
    public PmsProductResult getUpdateInfo(Long id) {
        return baseMapper.getUpdateInfo(id);
    }

    @Transactional
    @Override
    public int update(Long id, PmsProductParam productParam) {
        PmsProduct pmsProduct = productParam;
        productParam.setId(id);
        baseMapper.updateById(pmsProduct);
        // 阶梯价格
        productLadderService.remove(
                new LambdaQueryWrapper<PmsProductLadder>()
                .eq(PmsProductLadder::getProductId, id));
        // 商品满减价格

        productFullReductionService.remove(
                new LambdaQueryWrapper<PmsProductFullReduction>()
                .eq(PmsProductFullReduction::getProductId, id));

        // 商品会员价格
        memberPriceService.remove(
                new LambdaQueryWrapper<PmsMemberPrice>()
                        .eq(PmsMemberPrice::getProductId, id));
        // 商品sku库存信息
        skuStockService.remove(
                new LambdaQueryWrapper<PmsSkuStock>()
                        .eq(PmsSkuStock::getProductId, id)
        );
        // 商品参数及自定义属性
        productAttributeValueService.remove(
                new LambdaQueryWrapper<PmsProductAttributeValue>()
                        .eq(PmsProductAttributeValue::getProductId, id)
        );
        // 商品专题
        subjectProductRelationService.remove(
                new LambdaQueryWrapper<CmsSubjectProductRelation>()
                        .eq(CmsSubjectProductRelation::getProductId, id)
        );

        // 优选专区
        prefrenceAreaProductRelationService.remove(
                new LambdaQueryWrapper<CmsPrefrenceAreaProductRelation>()
                        .eq(CmsPrefrenceAreaProductRelation::getProductId, id)
        );

        // 商品阶梯价格
        relateAndInsertList(productLadderService, productParam.getProductLadderList(), id);
        // 商品满减价格
        relateAndInsertList(productFullReductionService, productParam.getProductFullReductionList(), id);
        // 商品会员价格
        relateAndInsertList(memberPriceService, productParam.getMemberPriceList(), id);
        // 商品库存信息
        relateAndInsertList(skuStockService, productParam.getSkuStockList(), id);
        // 商品自定义参数规格属性
        relateAndInsertList(productAttributeValueService, productParam.getProductAttributeValueList(), id);
        // 商品专题
        relateAndInsertList(subjectProductRelationService, productParam.getSubjectProductRelationList(), id);
        // 商品优选专区
        relateAndInsertList(prefrenceAreaProductRelationService, productParam.getPrefrenceAreaProductRelationList(), id);
        return 1;
    }

    private void relateAndInsertList(IService service, List dataList, Long productId) {
        try {
            // 判空
            if (CollectionUtils.isEmpty(dataList)) return;
            for (Object item : dataList) {
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
            }

            service.saveBatch(dataList);
        }catch (Exception e) {
            LOGGER.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }


}
